<template>
    <div id="app">
        <h2>管理员管理</h2>
        <!-- 创建管理员表单 -->
        <el-form :model="createForm" :rules="rules" ref="createFormRef" label-width="100px">
            <el-form-item label="管理员姓名" prop="name">
                <el-input v-model="createForm.name" placeholder="请输入管理员姓名"></el-input>
            </el-form-item>
            <el-form-item label="管理员账号" prop="username">
                <el-input v-model="createForm.username" placeholder="请输入管理员账号"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="createForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">创建管理员</el-button>
            </el-form-item>
        </el-form>

        <!-- 管理员列表 -->
        <el-table :data="managers" style="width: 100%">
            <el-table-column prop="username" label="账号"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column label="操作">
                <template v-slot="{ row }">
                    <el-button type="danger" @click="deleteManager(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
    name: "SuperAdmin",
    setup() {
        const createForm = ref({
            name: '', // 管理员姓名
            username: '',
            password: '',
        });
        const managers = ref([]);
        const createFormRef = ref(null);

        const rules = {
            username: [
                { required: true, message: '请输入管理员账号', trigger: 'blur' },
                { min: 4, message: '账号长度至少为4个字符', trigger: 'blur' }
            ],
            password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, message: '密码长度至少为6个字符', trigger: 'blur' }
            ]
        };

        // 实时验证函数
        const validateField = (field) => {
            createFormRef.value.validateField(field);
        };

        // 监听输入变化
        const watchEffect = () => {
            createForm.value.username = createForm.value.username.replace(/\s+/g, '');
            createForm.value.password = createForm.value.password.replace(/\s+/g, '');
            if (createForm.value.username.length < 4) {
                ElMessage.warning('账号长度至少为4个字符');
            }
            if (createForm.value.password.length < 6) {
                ElMessage.warning('密码长度至少为6个字符');
            }
        };


        const fetchManagers = async () => {
            try {
                const response = await axios.get('/api/v1/manager/list');
                if (response.data.code === 200) {
                    managers.value = response.data.data;
                    console.log(response.data.data);
                } else {
                    ElMessage.error('获取管理员列表失败');
                }
            } catch (error) {
                ElMessage.error('获取管理员列表请求失败');
            }
        };

        const createManager = async () => {
            try {
                const response = await axios.post('/api/v1/manager/create', createForm.value);
                console.log(response.data);
                if (response.data.code === 201) {
                    ElMessage.success('创建管理员成功');
                    fetchManagers(); // 重新获取管理员列表
                    resetForm(); // 重置表单
                } else {
                    ElMessage.error('创建管理员失败');
                }
            } catch (error) {
                ElMessage.error('创建管理员请求失败');
            }
        };

        const deleteManager = async (managerId) => {
            console.log(managerId);
            try {
                const response = await axios.post(`/api/v1/manager/delete`, 
                {
                     id: managerId  
                }
            );
                if (response.data.code === 200) {
                    ElMessage.success('删除管理员成功');
                    fetchManagers(); // 重新获取管理员列表
                } else {
                    ElMessage.error('删除管理员失败');
                }
            } catch (error) {
                ElMessage.error('删除管理员请求失败');
            }
        };

        const resetForm = () => {
            createForm.value.name = '';
            createForm.value.username = '';
            createForm.value.password = '';
        };
        const submitForm = () => {
            createFormRef.value.validate((valid) => {
                if (valid) {
                    createManager();
                } else {
                    ElMessage.error('表单验证失败');
                    return false;
                }
            });
        };

        onMounted(() => {
            fetchManagers(); // 初始化时获取管理员列表
        });

        return {
            createForm,
            managers,
            createFormRef,
            rules,
            fetchManagers,
            createManager,
            deleteManager,
            resetForm,
            submitForm,
            validateField,
            watchEffect,
        };
    },
};
</script>

<style scoped>
#app {
    padding: 20px;
}
</style>